package br.usp.poli.util;

import java.io.InputStream;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import br.usp.poli.entity.Occurrence;
import br.usp.poli.entity.Variable;
import br.usp.poli.util.db.HibernateUtil;
import br.usp.poli.ws.ExperimentManager;

import com.ricebridge.csvman.CsvManager;

/**
 * @author Leonardo Bessa
 * 
 */
public class XaropeImport {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		/*
		 * fillOccurrences(occurences,"xarope-1-1.csv","1"); //CSVFactoryTest
		 * factoryTest = new CSVFactoryTest(); //factoryTest.testCreateCSV();
		 * 
		 */
	}

	@SuppressWarnings("unchecked")
	public static void fillOccurrences(InputStream inputStream,
			String instrumentSerial) {
		ExperimentManager manager = new ExperimentManager();
		Set<Occurrence> occurences = new HashSet<Occurrence>();
		CsvManager csvManager = new CsvManager();
		csvManager.setStartLine(2);
		csvManager.setSeparator(",");
		csvManager.setRunInBackground(false);
		List<List<String>> data = csvManager.loadAsLists(inputStream);
		Variable[] concentracoes = new Variable[9];
		for (int i=1;i<10;i++){
			concentracoes[i-1] = findVariable("XAROPE", instrumentSerial,
			i+"0%(ml consumidos)");
		}
		for (List<String> line : data) {
			String dateString = line.get(0);
			int second = 0;
			int minute = 0;
			int hourOfDay = 12;
			int dayOfMonth = Integer.parseInt(dateString.substring(3, 5));
			int month = Integer.parseInt(dateString.substring(0, 2));
			int year = Integer.parseInt(dateString.substring(6, 10));
			// 10/22/2007 

			GregorianCalendar date = new GregorianCalendar(year, month - 1,
					dayOfMonth,hourOfDay,minute,second);
			
			for (int i=1;i<10;i++){
				String value = line.get(i);
				if (!value.isEmpty()) {
					Occurrence o = new Occurrence();
					o.setVariable(concentracoes[i-1]);
					o.setDate(date);
					o.setValue(value);
					occurences.add(o);
				}
			}

		}
		manager.submitOccurrences(occurences);
	}

	private static Variable findVariable(String instrumentModel,
			String instrumentSerial, String variableName) {
		Session session = HibernateUtil.getSession();
		Variable uniqueResult = (Variable) session.createCriteria(
				Variable.class).add(Restrictions.eq("name", variableName))
				.createAlias("instrument", "i").add(
						Restrictions.eq("i.model", instrumentModel)).add(
						Restrictions.eq("i.serial", instrumentSerial))
				.uniqueResult();
		return uniqueResult;
	}

}
